//
//  SalaryDateSetViewController.swift
//  mggz
//
//  Created by QinWei on 2018/1/17.
//  Copyright © 2018年 爱丽丝的梦境. All rights reserved.
//

import UIKit
//SelectTimeStyle.plist
class SalaryDateSetViewController: UIViewController {
    @IBOutlet weak var projectName: UILabel!
    @IBOutlet weak var spanner3view: SpinnerView!
    
    @IBOutlet weak var spanner1view: SpinnerView!
    @IBOutlet weak var spanner2view: SpinnerView!
    var monthArray = [String]()
    var dayArray = [String]()
    var timeArray = [String]()
    
    var selectPay = 0
    var selectDay = 0
    var selectTime = 0
    var orderId:String?
    
    var tap:UITapGestureRecognizer = {
        var t = UITapGestureRecognizer(target: self, action: #selector(closeSpanner(_:)))
        t.numberOfTapsRequired = 1
        t.numberOfTouchesRequired = 1
        t.cancelsTouchesInView = false
        return t
    }()
    
    @objc func closeSpanner(_ sender:UIGestureRecognizer){
        print("close")
    }
    
    override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
        print("touchesBegan")
        self.spanner1view.close()
        self.spanner2view.close()
        self.spanner3view.close()
    }
    
    override func viewDidLoad() {
        super.viewDidLoad()
        self.navigationItem.title = "结算设置"
        self.canSave(false)
        self.projectName.text = ProjectName
        
        var path = Bundle.main.path(forResource: "SelectTimeStyle", ofType: "plist")
        var selectRoot = NSDictionary(contentsOfFile: path!)
        var array1 = selectRoot?.object(forKey: "month") as? NSArray
        var array2 = selectRoot?.object(forKey: "day") as? NSArray
        var array3 = selectRoot?.object(forKey: "time") as? NSArray
        
        self.setArray(array1!, _newArray: &self.monthArray)
        self.setArray(array2!, _newArray: &self.dayArray)
        self.setArray(array3!, _newArray: &self.timeArray)
        
        
        
        
        self.spanner1view.setTitleList(self.monthArray, _rowHeight: 40)
        self.spanner1view.delegate = {
            index in
            self.selectPay = index
            self.canSave(true)
        }
        
        self.spanner2view.setTitleList(self.dayArray, _rowHeight: 40)
        self.spanner2view.delegate = {
            index in
            self.selectDay = index
            self.canSave(true)
        }
        
        self.spanner3view.setTitleList(self.timeArray, _rowHeight: 40)
        self.spanner3view.delegate = {
            index in
            self.selectTime = index
            self.canSave(true)
        }
        
        self.spanner1view.btnClick = {
            self.spanner2view.close()
            self.spanner3view.close()
        }
        
        self.spanner2view.btnClick = {
            self.spanner1view.close()
            self.spanner3view.close()
        }
        
        self.spanner3view.btnClick = {
            self.spanner1view.close()
            self.spanner2view.close()
        }
        
        //self.view.addGestureRecognizer(self.tap)
        
        
        var params:[String:Any] = ["MarketSupplyBaseID":ProjectId ?? ""]
        QWTextWithStatusHud("正在加载", target: self.view)
        MNetHttp.sharedInstance.postSingle(API_CALL_METHOD, method: .PayDay, params: &params, type: PayDayModel.self, success: { (bean,_) in
            QWHudDiss(self.view)
            guard var data = bean as? PayDayModel else{
                return
            }
            self.orderId = data.Result?.OrderId ?? ""
            self.selectPay = Int((data.Result?.SalaryAutoPeriod)! - 1.0)
            self.selectDay = Int((data.Result?.PayDay)! - 1.0)
            var time = data.Result?.PayTime?.getSubstring(1, end: 2)
            print("\(time)")
            self.selectTime = Int(time!)!
            self.spanner1view.setSelectSection(self.selectPay)
            self.spanner2view.setSelectSection(self.selectDay)
            self.spanner3view.setSelectSection(self.selectTime)
            
        }) { (error) in
            QWHudDiss(self.view)
            QWTextonlyHud("数据异常", target: self.view)
        }
        
    
    }
    
    func saveOperate(){
        QWTextWithStatusHud("正在保存", target: self.view)
        var month = self.dayArray[self.selectDay].getSubstring(0, end: self.dayArray[self.selectDay].count-1)
        var upTime:String?
        if month.count == 1{
            upTime = "2012-12-0\(month) \(self.timeArray[self.selectTime])"
        }else{
            upTime = "2012-12-\(self.dayArray[self.selectDay].getSubstring(0, end: 2)) \(self.timeArray[self.selectTime])"
        }
        var params:[String:Any] = ["MarketSupplyBaseID":ProjectId ?? "","SalaryAutoPeriod":(self.selectPay+1),"OrderId":self.orderId ?? "","SalaryPayTime":upTime ?? ""]
        MNetHttp.sharedInstance.postSingle(API_CALL_METHOD, method: .SaveGzJS, params: &params, type: SaveGzJs.self, success: { (bean,_) in
            QWHudDiss(self.view)
            guard var data = bean as? SaveGzJs else{
                return
            }
            if data.State == "OK"{
                QWTextonlyHud("保存成功", target: self.view)
                DispatchQueue.main.asyncAfter(deadline: DispatchTime.now()+1.5, execute: {
                    self.navigationController?.popViewController(animated: true)
                })
            }else{
                QWTextonlyHud("保存失败，请重试", target: self.view)
            }
        }) { (error) in
            QWTextonlyHud("保存失败，请重试", target: self.view)
        }
    }
    
    func setArray(_ oldarray:NSArray,_newArray newArray:inout [String]){
        for item in oldarray{
            newArray.append((item as? String ?? ""))
        }
    }
    
    func canSave(_ flag:Bool){
        var item = UIBarButtonItem(title: "保存", fontSize: 17, self, flag ? #selector(saveClick) : #selector(emptyClick), flag ? UIColor.LightBlue:UIColor.gray)
        self.navigationItem.rightBarButtonItem = item
        
    }
    
    @objc func emptyClick(){}
    
    @objc fileprivate func saveClick(){
        self.saveOperate()
        
    }
    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        
    }
    
}


